package com.ruoyi.web.controller.net;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.net.domain.ElementDhcp;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.ElementArpStatic;
import com.ruoyi.net.service.IElementArpStaticService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 网元-ARP配置-静态ARP配置Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-ARP配置-静态ARP配置")
@RestController
@RequestMapping("/element/arp/static")
public class ElementArpStaticController extends BaseController {
    @Autowired
    private IElementArpStaticService elementArpStaticService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 查询网元-ARP配置-静态ARP配置列表
     */
    @ApiOperation(value = "查询网元-ARP配置-静态ARP配置列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:static:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementArpStatic elementArpStatic) {
        startPage();
        List<ElementArpStatic> list = elementArpStaticService.selectElementArpStaticList(elementArpStatic);
        return getDataTable(list);
    }

    /**
     * 导出网元-ARP配置-静态ARP配置列表
     */
    @ApiOperation(value = "导出网元-ARP配置-静态ARP配置列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:static:export')")
    @Log(title = "网元-ARP配置-静态ARP配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementArpStatic elementArpStatic) {
        List<ElementArpStatic> list = elementArpStaticService.selectElementArpStaticList(elementArpStatic);
        ExcelUtil<ElementArpStatic> util = new ExcelUtil<ElementArpStatic>(ElementArpStatic.class);
        util.exportExcel(response, list, "网元-ARP配置-静态ARP配置数据");
    }

    /**
     * 获取网元-ARP配置-静态ARP配置详细信息
     */
    @ApiOperation(value = "获取网元-ARP配置-静态ARP配置详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:static:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementArpStaticService.selectElementArpStaticById(id));
    }

    /**
     * 新增网元-ARP配置-静态ARP配置
     */
    @ApiOperation(value = "新增网元-ARP配置-静态ARP配置", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:static:add')")
    @Log(title = "网元-ARP配置-静态ARP配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementArpStatic elementArpStatic) {
        return toAjax(elementArpStaticService.insertElementArpStatic(elementArpStatic));
    }

    /**
     * 修改网元-ARP配置-静态ARP配置
     */
    @ApiOperation(value = "修改网元-ARP配置-静态ARP配置", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:static:edit')")
    @Log(title = "网元-ARP配置-静态ARP配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementArpStatic elementArpStatic) {
        return toAjax(elementArpStaticService.updateElementArpStatic(elementArpStatic));
    }

    /**
     * 删除网元-ARP配置-静态ARP配置
     */
    @ApiOperation(value = "删除网元-ARP配置-静态ARP配置", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:static:remove')")
    @Log(title = "网元-ARP配置-静态ARP配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementArpStaticService.deleteElementArpStaticByIds(ids));
    }
    /**
     * 激活设备
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/activate/{id}")
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementArpStatic entity = elementArpStaticService.selectElementArpStaticById(id);
        entity.setStatus("1");
        if (sendXml(entity)){
            return toAjax(elementArpStaticService.updateElementArpStatic(entity));
        }else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementArpStatic entity = elementArpStaticService.selectElementArpStaticById(id);
        entity.setStatus("0");
        if (sendXml(entity)){
            return toAjax(elementArpStaticService.updateElementArpStatic(entity));
        }else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    /*<arp xmlns="http://fiberhome.com/fhnw/yang/ipservice/fos-arp">
    <arp-statics>
      <arp-static>
        <vrf-name>rrr34</vrf-name>
        <ip-addr>12.23.45.1</ip-addr>
        <mac-addr>00:00:00:00:00:01</mac-addr>
        <vlan-type>qinq</vlan-type>
        <qinq>
          <svlan-id>2</svlan-id>
          <cvlan-id>6</cvlan-id>
        </qinq>
      </arp-static>
    </arp-statics>
  </arp>*/
    private boolean sendXml(ElementArpStatic entity) {
        boolean isSend = true;
        // TODO: 2024/12/6 待与设备联调
        if (sysConfigService.selectDebugEnabled()) {
            NetElement netElement = netElementService.getCacheObject(entity.getElementId());
            deviceManager.getDevice(netElement.getIp());
            //"      <arp-static xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\" nc:operation=\"" + ("1".equalsIgnoreCase(entity.getStatus()) ? "create" : "remove") + "\">" +
            //
            StringBuilder xml = new StringBuilder();
            if ("1".equalsIgnoreCase(entity.getStatus())) {
                xml.append("<arp xmlns=\"http://fiberhome.com/fhnw/yang/ipservice/fos-arp\">" +
                        "    <arp-statics>" +
                        "      <arp-static xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\" nc:operation=\"create\">");
                if (StringUtils.isNotEmpty(entity.getVfrName())) {
                    xml.append("        <vrf-name>" + entity.getVfrName() + "</vrf-name>");
                }
                else {
                    xml.append("        <vrf-name>_public_</vrf-name>");
                }
                if (StringUtils.isNotEmpty(entity.getIp())) {
                    xml.append("        <ip-addr>" + entity.getIp() + "</ip-addr>");
                }
                if (StringUtils.isNotEmpty(entity.getMac())) {
                    xml.append("        <mac-addr>" + entity.getMac().replaceAll("-", ":") + "</mac-addr>");
                }
                if (StringUtils.isNotEmpty(entity.getSvlanId()) && StringUtils.isNotEmpty(entity.getClvanId())) {
                    xml.append("        <vlan-type>qinq</vlan-type>" +
                            "        <qinq>");
                    if (StringUtils.isNotEmpty(entity.getSvlanId())) {
                        xml.append("          <svlan-id>" + entity.getSvlanId() + "</svlan-id>");
                    }
                    if (StringUtils.isNotEmpty(entity.getClvanId())) {
                        xml.append("          <cvlan-id>" + entity.getClvanId() + "</cvlan-id>");
                    }

                    xml.append("        </qinq>");
                }
                else if (StringUtils.isNotEmpty(entity.getSvlanId())) {
                    // 若果vlan-type = dot1q
                    xml.append("        <vlan-type>dot1q</vlan-type>" +
                            "        <dot1q>" +
                            "          <vlan-id>" + entity.getSvlanId() + "</vlan-id>" +
                            "        </dot1q>");
                }
                xml.append(
                        "      </arp-static>" +
                                "    </arp-statics>" +
                                "  </arp>");
            }
            else {
                xml.append("<arp xmlns=\"http://fiberhome.com/fhnw/yang/ipservice/fos-arp\">" +
                        "    <arp-statics>" +
                        "      <arp-static xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\" nc:operation=\"remove\">");
                if (StringUtils.isNotEmpty(entity.getVfrName())) {
                    xml.append("        <vrf-name>" + entity.getVfrName() + "</vrf-name>");
                }
                if (StringUtils.isNotEmpty(entity.getIp())) {
                    xml.append("        <ip-addr>" + entity.getIp() + "</ip-addr>");
                }
                if (StringUtils.isNotEmpty(entity.getMac())) {
                    xml.append("        <mac-addr>" + entity.getMac().replaceAll("-", ":") + "</mac-addr>");
                }
                xml.append("      </arp-static>" +
                        "    </arp-statics>" +
                        "  </arp>");
            }
            logger.info("静态ARP配置激活xml：" + xml.toString());
            isSend = deviceManager.editConfig(xml.toString(), "merge");
        }
        return isSend;
    }
}